package com.llt.user.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.llt.common.core.domain.TableDataInfo;
import com.llt.common.core.enums.ExamListType;
import com.llt.common.core.enums.ResultCode;
import com.llt.common.core.utils.ThreadLocalUtil;
import com.llt.common.security.exception.ServiceException;
import com.llt.common.security.service.TokenService;
import com.llt.user.domain.exam.dto.ExamQueryDTO;
import com.llt.user.domain.exam.po.Exam;
import com.llt.user.domain.exam.vo.ExamVO;
import com.llt.user.domain.user.po.UserExam;
import com.llt.user.manager.ExamCacheManager;
import com.llt.user.mapper.exam.ExamMapper;
import com.llt.user.mapper.user.UserExamMapper;
import com.llt.user.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author llt
 * @since 2024-11-06
 */
@Service
public class UserExamServiceImpl extends ServiceImpl<UserExamMapper, UserExam> implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public int enter(Long examId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }

        // 获取用户id并查询是否已经报名
        Long userId = ThreadLocalUtil.getUserId();
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId)
        );
        if (userExam != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }

        // 添加缓存 u:e:l:userID --- examId
        examCacheManager.addUserExamCache(userId, examId);

        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);

        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO dto) {
        dto.setType(ExamListType.USER_EXAM_LIST.getValue());
        // 从 redis 当中获取竞赛列表长度, 判断缓存中是否有信息
        Long userId = ThreadLocalUtil.getUserId();
        Long total = examCacheManager.getListSize(dto.getType(), userId);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            // 从数据库查询竞赛列表
            PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(dto.getType(), userId);
        } else {
            examVOList = examCacheManager.getExamVOList(dto, userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }

        // 过滤筛选的时间
        examVOList = filterTime(examVOList, dto.getStartTime(), dto.getEndTime());

        // 计算总量
        total = (long) examVOList.size();

        return TableDataInfo.success(examVOList, total);
    }

    private List<ExamVO> filterTime(List<ExamVO> examVOList ,String start, String end) {
        // 过滤筛选的时间
        if (start != null) {
            // 将 dto 中开始时间和结束时间转为 LocalDateTime 类型
            LocalDateTime startTime = stringTransferTime(start);
            // 删除查出来早于要求的exam
            examVOList.removeIf(examVO -> examVO.getStartTime().isBefore(startTime));
        }
        if (end != null) {
            // 将 dto 中开始时间和结束时间转为 LocalDateTime 类型
            LocalDateTime endTime = stringTransferTime(end);
            // 删除查出来晚于要求的exam
            examVOList.removeIf(examVO -> examVO.getEndTime().isAfter(endTime));
        }

        return examVOList;
    }

    private LocalDateTime stringTransferTime(String str) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(str, formatter);
    }
}
